<script>
import {request} from "axios";

export default {
  name: "File.vue",
  data() {
    return {
      tableData: [],
      name: "",
      currentPage: 1,
      pageSize: 5,
      total: 0,
      loading: true,
      uploadUrl:this.baseUrl+'/file/upload',
      multipleSelection: [],
      headers:{token:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")).token:null}
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/file/selectAll", {
        params: {
          name: this.name,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.loading = false;
        this.total = res.data.total;

      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();

    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },
    handleFileUploadSuccess() {
      this.$message({
        message: '上传成功',
        type: 'success',
        center: true
      });
      this.load();
    },
    reset() {
      this.name = "";
      this.currentPage = 1;
      this.pageSize = 5;
      this.total = 0;
      this.load();
    },
    handleDelete(id) {
      this.request.delete("/file/delete/" + id).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            showClose: true,
            message:  res.msg,
            type: 'error'
          });
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((a) => a.id);
      console.log(this.multipleSelection);
    },
    handleBatchRemove() {
      let ids = this.multipleSelection;
      this.request.post("/file/deleteBatch", ids).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            center: true,
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    changeEnable(val) {
      let enable='启用';
      if(!val.enable){
        enable='禁用';
      };
      this.request.post("/file/update", val).then(res => {
        if (res.code == 200) {
          this.$message({
            message: enable+'成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            center: true,
            message: enable+'失败',
            type: 'error'
          });
        }
      })
    },
    download(url) {
      this.request.get("/file/"+url.split("/file/")[1],{
        responseType: 'blob'
      }).then(res=>{
        console.log(res)
        const blob = new Blob([res.data], { type: "application/octet-stream;charset=utf-8" })
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = decodeURI(
            res.headers["content-disposition"].split("filename=")[1]);
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      })
    },
    preview(url) {
      window.open('http://localhost:8012/onlinePreview?url=' + encodeURIComponent(window.btoa((url))));
    },
    headerBg({row,rowIndex}){
      if(rowIndex==0){
        return 'headerBgClass'
      }
    }
  }
}
</script>

<template>
  <div>
    <div>
      <el-input style="width:160px" v-model="name" suffix-icon="el-icon-search" placeholder="请输入文件名称"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning"style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin:10px 0px">
      <el-upload
          :action= "uploadUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleFileUploadSuccess"
          style="display: inline-block">
        <el-button type="primary" class="ml-5" icon="el-icon-upload">上传文件</el-button>
      </el-upload>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="你确定批量删除吗？"
          @confirm="handleBatchRemove"
          class="ml-5"
      >
        <el-button type="danger" class="ml-5" icon="el-icon-remove-outline" slot="reference">批量删除</el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData"
              border stripe
              v-loading="loading"
              max-height="550"
              :header-cell-class-name="headerBg"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255,225,255, 0.1)"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" align="center"></el-table-column>
      <el-table-column prop="id" label="ID" align="center">
      </el-table-column>
      <el-table-column prop="name" label="文件名称" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="type" label="文件类型" align="center">
      </el-table-column>
      <el-table-column prop="size" label="文件大小（kb）" align="center">
      </el-table-column>
      <el-table-column label="下载" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-download" @click="download(scope.row.url)"
                     :disabled="!scope.row.enable">下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="预览" align="center">
        <template slot-scope="scope">
          <el-button type="primary"  @click="preview(scope.row.url)" :disabled="!scope.row.enable">预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="changeEnable(scope.row)"

          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDelete(scope.row.id)"
          >
            <el-button type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding:10px 0px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.headerBgClass{
  background-color: #cccccc !important;
}
</style>
